//
//  ClubWuKongViewController.swift
//  77Club
//
//  Created by Apple on 2024/8/28.
//

import UIKit
import JXSegmentedView
import ZLPhotoBrowser

private let headerID    = "HWWuKongTopCateView"
private let titleHeaderID    = "WuKongTitleHeaderView"

class ClubWuKongViewController: ClubBaseViewController {

    var gid = ""
    private var topView = ClubInfoTopView()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubWuKongInfoCell.self,ClubDynamicListCell.self,ClubGameDetailCommitCell.self,ClubGameStrategyTopCell.self,ClubForumEquipCell.self,ClubForumImageTextCell.self,ClubSquareForumEmptyCell.self)
        tableView.register(ClubWuKongCateView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.register(ClubSquareDatailHeaderView.self, forHeaderFooterViewReuseIdentifier: titleHeaderID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 306.0.Scale
        tableView.sectionHeaderTopPadding = 8
        return tableView
    }()
    
    private var type = 999
    private var pageIndex = 1
    private var dataModel: ClubWuKongHotChatModel?
    private var commitData = [ClubGameDetailCommentListModel]()
    private var blockData: [ClubStrategyBlockModel]?
    private var model: ClubGameCommunityModel?
    private var isLoad = false
    private var playingIndexPath: IndexPath?
    private var currentVC = true

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        currentVC = false
        NotificationCenter.default.post(name: .stopDynamicAudioPlayer, object: nil)
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        currentVC = true
        NotificationCenter.default.addObserver(self, selector: #selector(toPostDetailVC), name: .forumToGameDetailVC, object: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        
        view.subviews{
            tableView
        }
        
        tableView.fillContainer()
        
        topView.frame = CGRect(x: 0, y: 0, width: .screenWidth, height: 170.0.Scale)
        tableView.tableHeaderView = topView
        
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
        
//        NotificationCenter.default.addObserver(self, selector: #selector(toPostDetailVC), name: .forumToGameDetailVC, object: nil)
    }
    
}

//MARK: - Data
extension ClubWuKongViewController {
    
    private func loadData(){
        
        ToastUtil.show()
        if type == 1 {
            
            Task{
                let res = await network.request(.commitList(gameId: gid, page: pageIndex, sortby: "0"),type: ClubGameDetailCommentListModel.self)
                ToastUtil.dismiss()
                tableView.refresh_end()
                if res.isSuccess, let models = res.models {
                    self.commitData = models
                    self.tableView.reloadData()
                }
            }
        }else if type == 2 {
            //攻略
            let netGroup = DispatchGroup()
            let workingQueue = DispatchQueue(label: "WuKongStrategyList")
            
            netGroup.enter()
            workingQueue.async {
                //攻略
                Task {
                    let res = await self.network.requestMore(.strategyInfo(communityID: self.gid, page: 1),type: ClubStrategyModel.self)
                    if res.isSuccess, let model = res.model {
                        self.blockData = model.blocks
                        netGroup.leave()
                    }
                }
            }
            netGroup.enter()
            workingQueue.async {
                
                Task{
                    let res = await self.network.request(.communityTop(communityID: self.gid),type: ClubGameCommunityModel.self)
                    if res.isSuccess, let model = res.model {
                        self.model = model
                        netGroup.leave()
                    }
                }
            }
            
            netGroup.notify(queue: workingQueue) {
                DispatchQueue.main.asyncAfter(deadline: .now()) {
                    ToastUtil.dismiss()
                    self.tableView.refresh_end()
                    self.tableView.reloadData()
                }
            }
        } else{
            Task{
                let res = await network.requestMore(.homeWuKong(gid: gid, page: pageIndex),type: ClubWuKongHotChatModel.self)
                ToastUtil.dismiss()
                tableView.refresh_end()
                if res.isSuccess, let model = res.model {
                    
                    self.dataModel = model
                    self.topView.bannarModel = model.banners
                    var dataArray = [ClubWuKongDataModel]()
                    if let models = model.data, models.count > 0 {
                        for var mdd in models {
                            guard let md = mdd.data else { return }
                            var mod = md
                            var itemSize: CGSize = .zero
                            if md.video.count > 0 {
                                itemSize = .zero
                            }else if md.img.count == 1 {
                                itemSize = CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
                            }else if md.img.count == 2 {
                                itemSize = CGSize (width: (CGFloat.screenWidth - 106.0.Scale)/2.0, height: 83.0.Scale)
                            }else if md.img.count > 2 {
                                let w = (CGFloat.screenWidth - 110.0.Scale)/3
                                itemSize = CGSize (width: w, height: w)
                            }else{
                                itemSize = .zero
                            }
                            mod.itemSize = itemSize
                            mdd.data = mod
                            dataArray.append(mdd)
                        }
                        self.dataModel?.data = dataArray
                    }
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    
    @objc func loadNewData() -> () {
        DispatchQueue.main.async {
            NotificationCenter.default.post(name: .stopDynamicAudioPlayer, object: nil)
        }
        pageIndex = 1
        loadData()
    }
    
    @objc func loadMoreData() -> () {

        if type == 2 {
            tableView.refresh_end(true)
            return
        }else{
            pageIndex += 1
            if type == 1 {                
                Task{
                    let res = await network.request(.commitList(gameId: gid, page: pageIndex, sortby: "0"),type: ClubGameDetailCommentListModel.self)
                    tableView.refresh_end()
                    if res.isSuccess, let models = res.models {
                        
                        if models.count > 0 {
                            self.commitData.append(contentsOf: models)
                        }
                        self.tableView.reloadData()
                    }
                }
            }else{
                Task{
                    let res = await network.requestMore(.homeWuKong(gid: gid, page: pageIndex),type: ClubWuKongHotChatModel.self)
                    tableView.refresh_end()
                    if res.isSuccess, let model = res.model {
                        
                        if let models = model.data, models.count > 0 {
                            var dataArray = [ClubWuKongDataModel]()
                            for var mdd in models {
                                guard let md = mdd.data else { return }
                                var mod = md
                                var itemSize: CGSize = .zero
                                if md.video.count > 0 {
                                    itemSize = .zero
                                }else if md.img.count == 1 {
                                    itemSize = CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
                                }else if md.img.count == 2 {
                                    itemSize = CGSize (width: (CGFloat.screenWidth - 106.0.Scale)/2.0, height: 83.0.Scale)
                                }else if md.img.count > 2 {
                                    let w = (CGFloat.screenWidth - 110.0.Scale)/3
                                    itemSize = CGSize (width: w, height: w)
                                }else{
                                    itemSize = .zero
                                }
                                mod.itemSize = itemSize
                                mdd.data = mod
                                dataArray.append(mdd)
                            }
                            self.dataModel?.data?.append(contentsOf: dataArray)
                        }else{
                            tableView.refresh_end(true)
                        }
                        self.tableView.reloadData()
                    }
                }
            }
        }
    }
    
//    @objc private func likeDynamic(dynamicID: String) {
//        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
//            Task {
//                let models = await network.request(.dynamicLike(type: "0", dynamicID: dynamicID))
//                if models.isSuccess {
//                    self.loadData()
//                }
//            }
//        }else{
//            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
//        }
//    }
    
    private func likeInfo(infoID: String) {
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            Task {
                let models = await network.request(.likeInfo(infoID: infoID))
                if models.isSuccess {
                    self.loadData()
                }
            }
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    private func likeCommit(commitID: String){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            Task{
                let res = await self.network.request(.likeGameCommit(commitID: commitID))
                if res.isSuccess {
                    self.loadData()
                }
            }
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubWuKongViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if type == 2 {
            return (self.blockData?.count ?? 0) + 2
        }
        return 1
     }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if type == 1 {
            if self.commitData.count == 0 {
                return 1
            }
            return self.commitData.count
        }else if type == 2 {
            if section == 0 {
                return 0
            }
            return 1
        }
        if self.dataModel?.data?.count ?? 0 == 0{
            return 1
        }
        return self.dataModel?.data?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if self.type == 1 {
            
            if self.commitData.count == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubSquareForumEmptyCell", for: indexPath) as! ClubSquareForumEmptyCell
                cell.titleString = "暂无评论~"
                return cell
            }else{
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameDetailCommitCell", for: indexPath) as! ClubGameDetailCommitCell
                cell.model = commitData[indexPath.row]
                cell.isWhite = false
    //            cell.didSelectImage = { index,images in
    //                self.selectImage(index: index, images: images)
    //            }
    //            cell.didSelectVideo = { url in
    //                self.selectVideo(url: url)
    //            }
                cell.clickLikeBlock = { id in
                    self.likeCommit(commitID: id)
                }
                return cell
            }
            
            
        }else if self.type == 2 {
            
            if self.blockData?.count == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubSquareForumEmptyCell", for: indexPath) as! ClubSquareForumEmptyCell
                cell.titleString = "暂无攻略~"
                return cell
            }
            
            if indexPath.section == 1 {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameStrategyTopCell", for: indexPath) as! ClubGameStrategyTopCell
                cell.models = model?.news
                cell.isWhite = true
                cell.jumpToDetail = { newsId, uid in
                    self.toDetailVC(newId: newsId)
                }
                return cell
            }else{
                //攻略
                let model = blockData?[indexPath.section - 2]
                if model?.image == 1 {
                    let cell = tableView.dequeueReusableCell(withIdentifier: "ClubForumImageTextCell", for: indexPath) as! ClubForumImageTextCell
                    cell.isWhite = true
                    cell.news = model?.news
                    return cell
                }else{
                    let cell = tableView.dequeueReusableCell(withIdentifier: "ClubForumEquipCell", for: indexPath) as! ClubForumEquipCell
                    cell.isWhite = true
                    cell.news = model?.news
                    return cell
                }
            }
            
        }else{
            if self.dataModel?.data?.count == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubSquareForumEmptyCell", for: indexPath) as! ClubSquareForumEmptyCell
                cell.titleString = "暂无帖子~"
                return cell
            }
            let infoM = self.dataModel?.data?[indexPath.row]
            if infoM?.type == 0 {
                //资讯
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubWuKongInfoCell", for: indexPath) as! ClubWuKongInfoCell
                cell.model = self.dataModel?.data?[indexPath.row]
                cell.likeBlock = { infoID in
                    self.likeInfo(infoID: infoID)
                }
                return cell
            }else {
                //动态
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubDynamicListCell", for: indexPath) as! ClubDynamicListCell
                cell.model = self.dataModel?.data?[indexPath.row]
//                cell.likeBlock = { dynamicID in
//                    self.likeDynamic(dynamicID: dynamicID)
//                }
                cell.jumpToDetail = { id in
                    let detailController = ClubDynamicDetailViewController()
                    detailController.dynamicID = id
                    detailController.updateDataBlock = {
                        self.loadNewData()
                    }
                    self.navigationController?.pushViewController(detailController, animated: true)
                }
                cell.didSelectImage = { index,images in
                    self.selectImage(index: index, images: images)
                }
                cell.didSelectVideo = { url in
                    self.selectVideo(url: url)
                }
                cell.toGameDetailVC = { gid in
                    let detailVC = ClubGameDetailViewController()
                    detailVC.gameId = gid
                    self.navigationController?.pushViewController(detailVC, animated: true)
                }
                return cell
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if type == 2 {
            return
        }
        if self.type == 1 {
            
            let detailVC = ClubGameDetailCommitDetailVC()
            detailVC.gameID = gid
            detailVC.gid = self.commitData[indexPath.row].id
            detailVC.updateDataBlock = {
                self.loadData()
            }
            self.navigationController?.pushViewController(detailVC, animated: true)
            
        }else{
            let model = self.dataModel?.data?[indexPath.row]
            if model?.type == 0 {
                let model = self.dataModel?.data?[indexPath.row].data
                let webView = ClubWebViewController()
                var urlStr = model?.webview_url ?? ""
                if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                    urlStr = urlStr + "&uid=\(uid)"
                }
                urlStr = urlStr + "&model=ios"
                webView.urlString = urlStr
                webView.titleName = "资讯详情"
                webView.ishiddenNav = true
                self.navigationController?.pushViewController(webView, animated: true)
                
            }else{
                let detailController = ClubDynamicDetailViewController()
                detailController.dynamicID = self.dataModel?.data?[indexPath.row].data?.id ?? ""
                self.navigationController?.pushViewController(detailController, animated: true)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if type == 1 && commitData.count > 0 {
            
            
        }
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if type == 2 && section > 1 {
            
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: titleHeaderID) as! ClubSquareDatailHeaderView
            header.titleString = self.blockData?[section - 2].name
            return header
            
        }else if type == 2 && section == 1 {
            return nil
        }else{
          
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! ClubWuKongCateView
            if !isLoad {
                header.gid = self.gid
            }
            header.updateCateData = { cateID in
                if cateID == 4 {
                    self.navigationController?.pushViewController(ClubGameToolsViewController(), animated: true)
                }  else {
                    self.tableView.resetNoMoreInfo()
                    self.type = cateID
                    self.loadNewData()
                }
            }
            isLoad = true
            return header
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if type == 2 && section > 1 {
            
            return 44.0.Scale
        }else if type == 2 && section == 1 {
            
            return 0
        }
        return 40.0.Scale
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard let visibleCells = tableView.visibleCells as? [ClubDynamicListCell] else { return }
            
        // 获取 TableView 的中心位置
        let tableViewCenter = tableView.bounds.size.height / 2 + tableView.contentOffset.y

        for cell in visibleCells {
            guard let indexPath = tableView.indexPath(for: cell) else { continue }
            let cellCenterY = cell.center.y

            // 判断 Cell 中心是否接近 TableView 中心
            if abs(cellCenterY - tableViewCenter) < 50 { // 设定 50 为接近程度的阈值
                if playingIndexPath != indexPath {
                    playingIndexPath = indexPath
                    cell.playVideo()  // 播放视频
                }
            } else {
                if playingIndexPath == indexPath {
                    cell.pauseVideo()  // 暂停视频
                    playingIndexPath = nil
                }
            }
        }
    }
    
}

//MARK: action
extension ClubWuKongViewController {
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func selectVideo(url: String) {
        
        let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .video
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func toCommunityController(communityId: String){
        
//        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            let community = ClubSquareDatailViewController()
            community.communityId = communityId
            self.navigationController?.pushViewController(community, animated: true)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                NotificationCenter.default.post(name: .toStrategyDetailVC, object: nil)
            }
//        }else{
//            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
//        }
        
    }
    
    @objc private func toPostDetailVC(noti: Notification){
        
        if let newsID = noti.userInfo?["infoID"] as? String {
            self.toDetailVC(newId: newsID)
        }
    }
    
    private func toDetailVC(newId: String){
        
        let detailVC = ClubForumDetailViewController()
        detailVC.newId = newId
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
}

extension ClubWuKongViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
